package com.kinon.ceshiaccount.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.activity.OrderPayActivity;
import com.kinon.ceshiaccount.adapter.DiningTypeAdapter;
import com.kinon.ceshiaccount.adapter.SettlementAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.RoleBean;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.util.LunchTypeUtil;
import com.kinon.ceshiaccount.util.MyDecimalFormat;
import com.kinon.ceshiaccount.util.MyShowDialog;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SoundPoolManage;
import com.kinon.ceshiaccount.util.SysTimeManage;
import com.kinon.ceshiaccount.util.ToastUtil;
import com.kinon.ceshiaccount.view.CustomDialog;
import com.kinon.ceshiaccount.view.computer.ComputerNumView;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by luohao on 2017-06-16.
 * 结算页面，负责金额计算生成结算订单
 */

public class SettlementFragment extends BaseFragment implements
        ComputerNumView.OnComputerListener {
    private View mView;
    /**结算的总价*/
    private TextView tv_total;
    /**显示就餐类型的布局*/
    private RelativeLayout rl_select;
    /**输入的金额*/
    private EditText et_money;
    /**计算记录的集合*/
    private ListView list_money;
    /**计算机*/
    private ComputerNumView cview_settlement;
    /**选择就餐类型*/
    private GridView grid_diningType;
    private TextView tv_sType;
    /**加的符号*/
    private TextView et_Spuls;

    /**表示输入的数字*/
    private String etNum="";
    private ArrayList<String> moneyList= new ArrayList<>();
    private SettlementAdapter adapter=null;
    /**不包括输入框里的总价*/
    private Double totalMoney=0.0;
    /**显示的总价*/
    private Double showTotalMoney=0.0;

    private Context context;
    /*就餐类型相关*/
    private int mType=0;
    private ArrayList<RoleBean> binings=null;
    private DiningTypeAdapter diningAdapter=null;
    private int mIndex=0;
    private long firstTime;

//    /**唯一识别码*/
//    private long nonce_str;
    ToastUtil toastUtil=new ToastUtil();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        mView=inflater.inflate(R.layout.fragment_settlement_layout,container,false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SoundPoolManage.getInstance().soundpPlay(2);
        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            if(binings!=null && diningAdapter!=null){
              int timeArea= (int)((System.currentTimeMillis()-firstTime)/(1000*60*60));
                setDiningType();
                if(timeArea>=2){
                    dialogSelect();
                }
            }
        }
    }

    /**获取默认的刷卡类型*/
    private void setDiningType(){
        int  type=SysTimeManage.getInstage().getOrderType(System.currentTimeMillis());
        for(int i=0;i<binings.size();i++){
            if(binings.get(i).getId()==type){
                mIndex=i;
                mType=type;
                continue;
            }
        }
        diningAdapter.selectItem(mIndex);
        diningAdapter.notifyDataSetChanged();
        tv_sType.setText(LunchTypeUtil.lunchType(mType));
    }

    private void initView() {
        context= AccountApplication.getInstance();
        tv_total= (TextView) mView.findViewById(R.id.tv_total);
        et_money= (EditText) mView.findViewById(R.id.et_money);
        list_money= (ListView) mView.findViewById(R.id.list_money);
        cview_settlement= (ComputerNumView) mView.findViewById(R.id.cview_settlement);
        grid_diningType= (GridView) mView.findViewById(R.id.grid_diningType);
        rl_select= (RelativeLayout) mView.findViewById(R.id.rl_select);
        tv_sType= (TextView) mView.findViewById(R.id.tv_sType);

        et_Spuls=(TextView) mView.findViewById(R.id.et_Spuls);
        et_money.addTextChangedListener(watcher);

        cview_settlement.setOnComputerListener(this);
        adapter=new SettlementAdapter(getActivity(),moneyList);
        list_money.setAdapter(adapter);

        showDiningType();
        tv_sType.setText(LunchTypeUtil.lunchType(mType));
    }

    private void showDiningType(){
        String roles=SPManage.getInstance().getString("roles");
        if (TextUtils.isEmpty(roles)){
            return;
        }
        Gson gson=new Gson();
          binings=new ArrayList<>();
        try {
            JSONArray array=new JSONArray(roles);
            for(int i=0;i<array.length();i++){
                RoleBean bean=gson.fromJson(array.get(i).toString(),RoleBean.class);
                if(bean.getId()!=12) {
                    binings.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(binings.size()==0){
            rl_select.setVisibility(View.GONE);
            return;
        }
        mType=binings.get(0).getId();
        if(binings.size()<=1){
            rl_select.setVisibility(View.GONE);
            return;
        }

        grid_diningType.setNumColumns(binings.size());
          diningAdapter=new DiningTypeAdapter(context,binings);
        grid_diningType.setAdapter(diningAdapter);
        setDiningType();
        dialogSelect();
        grid_diningType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mIndex=i;
                mType=binings.get(i).getId();
                tv_sType.setText(LunchTypeUtil.lunchType(mType));
                diningAdapter.selectItem(i);
                diningAdapter.notifyDataSetChanged();
            }
        });

    }

    private void dialogSelect(){
         firstTime=System.currentTimeMillis();
         CustomDialog  dialog=new CustomDialog(1, getContext(),null, binings,
                mIndex,new CustomDialog.DialogClickListener() {
                    @Override
                    public void onDialogClick(int btn) {
                        mIndex=btn;
                        mType=binings.get(btn).getId();
                        tv_sType.setText(LunchTypeUtil.lunchType(mType));
                        diningAdapter.selectItem(btn);
                        diningAdapter.notifyDataSetChanged();
                    }
                });
        dialog.show();
    }



    private TextWatcher watcher=new TextWatcher() {
        //text  输入框中改变前的字符串信息  start 输入框中改变前的字符串的起始位置
        //count 输入框中改变前后的字符串改变数量一般为0 after 输入框中改变后的字符串与起始位置的偏移量
        @Override
        public void beforeTextChanged(CharSequence text,int start,int icount,int iafter) {
        }
        //text  输入框中改变后的字符串信息 start 输入框中改变后的字符串的起始位置
        // count输入框中改变前的字符串的位置 默认为0 after 输入框中改变后的一共输入字符串的数量
        @Override
        public void onTextChanged(CharSequence text,int start,int icount,int iafter){
        }

        //editable  输入结束呈现在输入框中的信息
        @Override
        public void afterTextChanged(Editable editable) {
            double price=0.0;
            if(editable.length()==0){
                price=0.0;
            }else if (editable.toString().trim().equals(".")){
                return;
            }else{
                price =Double.parseDouble(editable.toString().trim());
            }
            showTotalMoney=totalMoney+price;
            String strShowMoney=String.valueOf(showTotalMoney);
            if(strShowMoney.length()>10){
                strShowMoney=MyDecimalFormat.dFormat(showTotalMoney);
            }
            tv_total.setText(strShowMoney);
//            totalMoney=Double.parseDouble(editable.toString().trim());
        }
    };

    /**
     * 计算器的点击监听事件
     * @param num
     */
    @Override
    public void onComputerListener(String num) {
        numCount(num);
    }

    /**
     * 计算器的运算
     * @param num 返回的键对应的string
     */
    private void numCount(String num){
        //p代表.
         if (num.equals("p")){
             //小数点的计算
             counPoint();
        }
        //j代表加
        else if (num.equals("j")){
             //加号计算
             countPlus();
        }
        //c代表清除
        else if (num.equals("c")){
             //清除计算
             countClear();
        }
        //o代表完成
        else if (num.equals("o")){
            long nonce_str=System.currentTimeMillis();
             //判断是否是紧急状态
             if(!Constant.URGENT_TYPE){
                 saveorder(nonce_str+"");
             }else{
                 urgentJiesuan (true,"",nonce_str+"");
//               urgentJiesuan();
             }

        }
        //d代表删除上一个
        else if (num.equals("d")){
             //删除上一个
             countDelete();
        }
        //除了上面几种特殊键就是数字键
        else{
             if(etNum.length()>=7){
                 return;
             }
             etNum+=num;
             et_money.setText(etNum);
         }
    }

    /**
     * 小数点的计算
     */
    private void counPoint(){
        //判断etNum中是否已经存在.
        if(etNum.contains(".")){
            return;
        }else{
            etNum+=".";
            et_money.setText(etNum);
        }
    }

    private void saveorder(final String nonce_str){
        MyShowDialog.showLoadingDialog(getContext(),"订单生成中...");
        Call<BaseBean<String>> call= HttpManage.getReqLunchApi().saveNewOrder(
                SPManage.getInstance().getToken(),showTotalMoney+"",mType+"",nonce_str);
        call.enqueue(new MyCallback<BaseBean<String>>() {
            @Override
            public void onSuccess(Call<BaseBean<String>> call, Response<BaseBean<String>> response) {
                MyShowDialog.closeLoadingDialog();
                BaseBean<String> base=response.body();
                urgentJiesuan(false,base.getData(),nonce_str);
            }

            @Override
            public void onError(int code, String error) {
                MyShowDialog.closeLoadingDialog();
                //超时默认为成功
                if(code==Constant.ERROR_TIMEOUT_CODE){
                    urgentJiesuan (true,"",nonce_str);
                }else{
//                   Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
                    toastUtil.Short(error)
                            .setToastBackground(Color.WHITE,0).show();
                }

            }
        });
    }

    /**紧急结算 urgent=true紧急模式 */
    private void urgentJiesuan (boolean urgent,String orderid,String nonce_str){
        Intent intent = new Intent(getContext(), OrderPayActivity.class);
        intent.putExtra("total",tv_total.getText().toString().trim());
        intent.putExtra("diningType",mType);
        intent.putExtra("oridrid",orderid);
        intent.putExtra("urgent",urgent);
        intent.putExtra("nonce_str",nonce_str);
        startActivity(intent);
        //完成跳转然后清空数据
        countClear();
    }

    /**
     * 清除计算
     */
    private void countClear(){
        et_Spuls.setVisibility(View.GONE);
        etNum="";
        totalMoney=0.0;
        showTotalMoney=0.0;
        tv_total.setText(totalMoney+"");
        et_money.setText(etNum);
        //清空集合
        moneyList.clear();
        adapter.notifyDataSetChanged();
    }

    /**
     * 加号计算
     */
    private void countPlus(){
        //判断输入框里是否有值 否直接跳出判断
        if(TextUtils.isEmpty(etNum)){
            return;
        }
        //判断是否是第一次
        if(moneyList.size()==0){
            et_Spuls.setVisibility(View.VISIBLE);
            totalMoney=showTotalMoney;
            moneyList.add(etNum);
            etNum="";
            et_money.setText(etNum);
            adapter.notifyDataSetChanged();
            return;
        }
        //判断加号是否显示，显示直接加入集合不显示先显示
        if(et_Spuls.getVisibility()==View.VISIBLE) {
//                 et_Spuls.setVisibility(View.VISIBLE);
            totalMoney = showTotalMoney;
            moneyList.add("+" + etNum);
            etNum = "";
            et_money.setText(etNum);
            adapter.notifyDataSetChanged();
        }else{
            et_Spuls.setVisibility(View.VISIBLE);
        }
    }



    /**
     * 删除上一个
     */
    private void countDelete(){
        if(etNum.trim().length()>0){
            etNum=etNum.substring(0,etNum.length()-1);
            et_money.setText(etNum);
        }else{
            et_Spuls.setVisibility(View.GONE);
            if(moneyList.size()==0){
                return;
            }
            //得到list集合的最后一个字符
            String reNum=moneyList.get(moneyList.size()-1);
            //判断字符中是否有+的符号
            if(reNum.contains("+")){
                etNum=reNum.substring(1);
                et_money.setText(etNum);
                et_Spuls.setVisibility(View.VISIBLE);
            }else{
                et_Spuls.setVisibility(View.GONE);
                etNum=reNum;
                et_money.setText(etNum);
            }
            showTotalMoney=showTotalMoney-(Double.parseDouble(reNum.trim()));

            totalMoney=totalMoney-(Double.parseDouble(reNum.trim()));

            String strShowMoney=String.valueOf(showTotalMoney);
            if(strShowMoney.length()>10){
                strShowMoney=MyDecimalFormat.dFormat(showTotalMoney);
            }
            tv_total.setText(strShowMoney);
//            tv_total.setText(showTotalMoney+"");
            moneyList.remove(moneyList.size()-1);
            adapter.notifyDataSetChanged();
        }
    }
}
